﻿using System;

namespace ZyGame
{
    public sealed class ScheduleCancelToken : IDisposable
    {
        private bool isCancel;
        private Action cancelCallback;
        internal void Register(Action canceled)
        {
            this.cancelCallback = canceled;
        }

        internal void Restart()
        {
            isCancel = false;
        }

        public void Cancel()
        {
            if (isCancel)
            {
                throw new Exception("the task is already cancelled");
            }
            isCancel = true;
            cancelCallback?.Invoke();
        }

        public bool TryCancel()
        {
            if (isCancel)
            {
                return false;
            }
            Cancel();
            return isCancel;
        }
        public void Dispose()
        {
            cancelCallback = null;
            isCancel = false;
        }
    }
}